package com.sleepless.my.service.impl;

import com.sleepless.my.entity.CommentEntity;
import com.sleepless.my.entity.UsersEntity;
import com.sleepless.my.entity.VideoEntity;
import com.sleepless.my.io.RestBean;
import com.sleepless.my.io.request.Comment.CreateCommentReq;
import com.sleepless.my.io.request.Comment.DeleteCommentReq;
import com.sleepless.my.io.request.Comment.GetCommentsReq;
import com.sleepless.my.repository.CommentRepository;
import com.sleepless.my.repository.UsersRepository;
import com.sleepless.my.repository.VideoRepository;
import com.sleepless.my.service.CommentService;
import jakarta.annotation.Resource;
import jakarta.persistence.criteria.Predicate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class CommentServiceImpl implements CommentService {
    @Resource
    private CommentRepository commentRepository;

    @Resource
    private VideoRepository videoRepository;

    @Resource
    private UsersRepository usersRepository;

    @Override
    public Object createComment(CreateCommentReq req) {
        VideoEntity videoEntity = videoRepository.findById(req.getVideoId()).orElse(null);
        UsersEntity usersEntity = usersRepository.findByuuid(req.getUuid());
        CommentEntity commentEntity=CommentEntity.builder().content(req.getContent()).videoEntity(videoEntity).usersEntity(usersEntity).build();
        commentRepository.save(commentEntity);
        return commentEntity.getCommentID();
    }

    @Override
    public Object deleteComment(DeleteCommentReq req) {
        commentRepository.deleteById(req.getCommentId());
        return null;
    }

    @Override
    public Object getComments(GetCommentsReq req) {
        Pageable pageable = PageRequest.of(req.getPageReq().getPage(), req.getPageReq().getLimit());
        Specification<CommentEntity> spec = (root, query, cb) ->{
            List<Predicate> predicates=new ArrayList<>();
            return cb.and(predicates.toArray(new Predicate[0]));
        };
        return commentRepository.findAll(spec, pageable);
    }

    @Override
    public Object getComment(Integer commentId) {
        if(!commentRepository.existsById(commentId)) {
            return RestBean.Code.评论不存在;
        }
        return commentRepository.findById(commentId).orElse(null);
    }
}
